package com.spx.chapter05.transform;

import com.spx.chapter05.pojo.Event;
import com.spx.util.SampleDataUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * create by undeRdoG on  2022-04-30  14:07
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class FlatMapTest {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<Event> dataStreamSource = env.fromCollection(SampleDataUtil.getSample());

        // 获取event的每个字段，返回每个字段的长度
        SingleOutputStreamOperator<Tuple2<String, Integer>> res = dataStreamSource.flatMap(new FlatMapFunction<Event, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(Event event, Collector<Tuple2<String, Integer>> collector) {
                collector.collect(Tuple2.of(event.user.trim(), event.user.trim().length()));
                collector.collect(Tuple2.of(event.url.trim(), event.url.trim().length()));
                collector.collect(Tuple2.of(event.timestamp.toString(), event.timestamp.toString().length()));
            }
        });

        res.print();

        env.execute();

    }
}
